<?php
/**
 * Created by PhpStorm.
 * User: 程阳
 * Date: 2017/2/23
 * Time: 8:58
 */

namespace Admin\Controller;


use Common\Controller\AdminController;
use Common\Model\GoodsModel;
use Org\Util\Data;

class GoodsController extends AdminController
{
    protected $db;
    public function __init(){
        $this->db = new GoodsModel();
    }

    public function lists(){
        $model = M('Goods'); // 实例化User对象
        if(I('get.search') || I('get.brand') || I('get.class')){
            if(I('get.search')){
                $key = I('get.search');
                $map['gname'] = array('like','%' . $key . '%');
            }
            if(I('get.brand')){
                $bid = I('get.brand');
                $map['bid'] = array('eq',$bid);
            }
            if(I('get.class')){
                $cid = I('get.class');
                $map['cid'] = array('eq',$cid);
            }
            $count      = $model->where($map)->count();// 查询满足要求的总记录数
            if(I("get.p") > ceil($count / 2)){
                $this->redirect('lists', array('search' => $key));
            }
            $Page       = new \Think\Page($count,2);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $Page->setConfig('header',"共 <span style='color:red'>%TOTAL_ROW%</span> 条记录");
            $Page->setConfig('prev','上一页');
            $Page->setConfig('next','下一页');
            $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
            $show       = $Page->show();// 分页显示输出
// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $list = $model->where($map)->order('gptime')->limit($Page->firstRow.','.$Page->listRows)->select();
        }else{
            $count      = $model->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,2);// 实例化分页类 传入总记录数和每页显示的记录数(6)
            $Page->setConfig('header',"共 <span style='color:red'>%TOTAL_ROW%</span> 条记录");
            $Page->setConfig('prev','上一页');
            $Page->setConfig('next','下一页');
            $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
            $show       = $Page->show();// 分页显示输出
            $list = $model->order('gptime')->limit($Page->firstRow.','.$Page->listRows)->select();
        }

        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出

        $brandData = M("Brand")->select();
        $this->assign("brandData",$brandData);
        $classData = M("Class")->getField("pid",true);
        $map['cid'] = array('not in',$classData);
        $map['pid'] = array('neq',0);
        $classData = M("Class")->where($map)->select();
        $this->assign("classData",$classData);

        $this->display();
    }

    public function addGoods(){

        if(IS_POST){
            $res = $this->db->addGoods();
            if($res['valid']){
                $this->success($res['message'],u('lists'));die;
            }
            $this->error($res['message']);die;
        }

        $classData = (new Data())->tree(M('Class')->select(),'cname');
        $this->assign('classData',$classData);
        $brandData = M('Brand')->select();
        $this->assign('brandData',$brandData);
        $this->display();
    }

    // ajax异步获得分类对应的属性
    public function ajaxGetAttr(){
        if(IS_AJAX){
            $tid = I('post.tid');
            $attrData = M('Tproperty')->where("tid = '{$tid}'")->select();
            foreach($attrData as $k => $v){
                $attrData[$k]['tpvalue'] = explode(',',$v['tpvalue']);
            }
            $this->ajaxReturn($attrData);
        }
    }

    // ajax异步通过上传图片插件进行图片上传
    public function ajaxUpload(){
        $this->upload();
    }

    public function editGoods(){
        $gid = I('get.gid');
        // 获得所有分类数据
        $classData = (new Data())->tree(M('Class')->select(),'cname');
        $this->assign('classData',$classData);
        // 获得所有品牌数据
        $brandData = M('Brand')->select();
        $this->assign('brandData',$brandData);

        // 关联商品表和商品详情表取数据
        $oldData = $this->db->alias('g')->join('xm_goods_details gd ON g.gid=gd.gid')->where("g.gid='{$gid}'")->find();
        // 将大图路径转换为数组
        $oldData['big'] = explode('|',$oldData['big']);
        $this->assign('oldData',$oldData);

        // 处理属性和规格数据
        // 1.先处理属性数据
        // 先根据商品所属类型从类型属性表里取出该类型所对应的属性，将属性分配到前台进行遍历，然后再从商品属性表里取出该商品所对应的属性，将数据
        // 组成一个数组，然后判断类型属性是否在商品已经添加的属性数组里，进行默认选中效果
        // $attrData = M('GoodsAttr')->alias('ga')->join('xm_tproperty tp on ga.tpid=tp.tpid')->where("ga.gid='{$gid}'")->select();
        $attrData = M('Tproperty')->where("tid='{$oldData['tid']}' and tptype=1")->select();
        foreach($attrData as $k => $v){
            $attrData[$k]['tpvalue'] = explode(',',$v['tpvalue']);
        }
        // 取得添加商品时所选择的属性
        $hasAddAttr = M('GoodsAttr')->where("gid='{$gid}'")->getField("gattr",true);
        $this->assign('attrData',$attrData);
        $this->assign('hasAddAttr',$hasAddAttr);

        // 2.处理规格数据
        // 将商品属性表和类型属性表进行关联查询，取出要编辑的商品所添加的规格名和规格值，并将商品对应类型的规格重组为数组
        $specData = M('Tproperty')->alias('tp')->join('xm_goods_attr ga on tp.tpid=ga.tpid')->where("ga.gid='{$gid}' and tptype=2")->select();
        foreach($specData as $k => $v){
            $specData[$k]['tpvalue'] = explode(',',$v['tpvalue']);
        }
//        dd($specData);
        $this->assign('specData',$specData);

        if(IS_POST){
            $res = $this->db->addGoods();
            if($res['valid']){
                $this->success($res['message'],u('lists'));die;
            }
            $this->error($res['message']);die;
        }
        $this->display();
    }

    public function delGoods(){
        $gid = I('post.id');
        $res = $this->db->where("gid='{$gid}'")->delete();
        if($res){
            $res1 = M('GoodsDetails')->where("gid='{$gid}'")->delete();
        }
        if($res1){
            $res2 = M('GoodsAttr')->where("gid='{$gid}'")->delete();
        }
        if($res2){
            return show(1,'删除成功');
        }else{
            return show(0,'删除失败');
        }
    }
}